#!/bin/bash

# This is a script for stress testing of little file read and write.

export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
export LC_ALL=en_US.UTF-8

source config.sh
source functions.sh

# Check option.
if [[ -z ${1} ]]; then
	echo "Usage: ${0} <dir_to_test>"
	exit 1
elif [[ ! -d ${1} ]]; then
	echo "${1} not exist or ${1} is not directory."
	exit 1
elif [[ ! -x ${1} ]]; then
	echo "${1} is not writable."
	exit 1
elif (( `find ${1} | wc -l` != 1 )); then
	echo "${1} is not empty."
	exit 1
fi
TEST_DIR=`echo ${1} | sed 's/\/$//'`

# Adjust config value.
if (( ${MAX_SIZE} > 32767 )); then
	MAX_SIZE=32767
fi
if (( ${MAX_SIZE} < 0 )); then
	MAX_SIZE=0
fi

# Initial.
if [[ ! -d ${TMP_DIR} ]]; then
	mkdir ${TMP_DIR}
fi
rm -rf ${TMP_DIR}/* --preserve-root
# mkdir for lock file.
mkdir ${TMP_DIR}/lock
# mkdir for write temp file.
mkdir ${TMP_DIR}/cache
rm -f ${TMP_DIR}/let_us_exit.status
rm -f ${TMP_DIR}/process_*.pid

# Start process
func_start

while true
do
	#sleep 1
	read -p "command >> " COMMAND
	if [[ ${COMMAND} == "exit" ]]; then
		func_stop
		break
	elif [[ ${COMMAND} == "start" ]]; then
		func_start
	elif [[ ${COMMAND} == "stop" ]]; then
		func_stop
	elif [[ ${COMMAND} == "restart" ]]; then
		func_stop
		func_start
	elif [[ ${COMMAND} == "status" ]]; then
		func_status
	elif [[ "`echo ${COMMAND} | awk '{print $1}'`" == "set" ]]; then
		KEY_VALUE="`echo ${COMMAND} | sed 's/^set\ //' | sed 's/\ //g'`"
		if [[ "`echo ${KEY_VALUE} | awk -F'=' '{print $1}'`" == "TMP_DIR" ]]; then
			echo "You can\'t change the value of TMP_DIR."
		else
			echo ${KEY_VALUE} > ${TMP_DIR}/config.tmp
			export ${KEY_VALUE}
		fi
	elif [[ "`echo ${COMMAND} | awk '{print $1}'`" == "get" ]]; then
		KEY=`echo ${COMMAND} | awk '{print $2}'`
		echo ${!KEY}
	elif [[ -z "${COMMAND}" ]]; then
		continue
	else
		echo "command not found."
	fi

done

# Do some clean
rm -rf ${TMP_DIR} --preserve-root

if [[ "${EMPTY_AFTER_TEST}" == "1" ]]; then
	rm -rf ${TEST_DIR}/* --preserve-root
fi

